package com.project.myproject.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

/**
 * @author Honorable(mabingqian)
 * @description
 * @date 2020/8/13 10:04
 * @update （更新、优化，注明点）
 */
public class NIOClient {

    private Selector selector;

    public void initClient(String ip, int port) throws IOException {
        //获取一个通道
        SocketChannel channel = SocketChannel.open();
        //设置为非阻塞
        channel.configureBlocking(false);
        //通道选择器打开
        this.selector = Selector.open();
        //绑定端口和IP
        channel.connect(new InetSocketAddress(ip, port));
        //将通道与通道选择器进行板顶，当前事件选择为连接，等待连接，需要在listen中通过finishConnection完成连接
        channel.register(selector, SelectionKey.OP_CONNECT);
    }


    public void listen() throws IOException {
        while (true) {
            //当注册的事件到达时，方法返回；否则,该方法会一直阻塞
            selector.select();
            // 获得selector中选中的项的迭代器
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                //获取事件
                SelectionKey key = iterator.next();
                //删除掉，防止重复处理
                iterator.remove();
                //如果事件是连接事件
                if (key.isConnectable()) {
                    //获取通道
                    SocketChannel channel = (SocketChannel) key.channel();
                    //判断是否正在连接，通过finishConnect完成连接
                    if (channel.isConnectionPending()) {
                        channel.finishConnect();
                    }
                    //设置通道为非阻塞
                    channel.configureBlocking(false);
                    //连接成功，给服务端发送一条成功消息
                    channel.write(ByteBuffer.wrap(new String("向服务端发送一条消息").getBytes()));
                    //连接成功了，则开始接受消息，此时需要修改事件选择器的事件类型为可读
                    channel.register(this.selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    channel.read(buffer);
                    byte[] data = buffer.array();
                    String msg = new String(data, StandardCharsets.UTF_8).trim();
                    System.out.println("客户端收到消息：" + msg);
                    channel.write(buffer);
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        NIOClient client = new NIOClient();
        client.initClient("localhost", 8000);
        client.listen();
    }
}
